package org.example.https;

import javax.net.ssl.*;
import java.net.URL;
import java.net.URLConnection;

/**
 * @author hh
 * @since 2025/2/16
 */
public class SecureHttpClient {

    public static void sentRequest(String path) throws Exception {
        // 创建客户端SSLContext上下文
        SSLContext sslContext = SSLContextFactory.getSslContext();
        // 创建安全套接字工厂
        SSLSocketFactory socketFactory = sslContext.getSocketFactory();
        // 主机名称校验
        HostnameVerifier hostnameVerifier = new HostnameVerifier() {
            @Override
            public boolean verify(String hostName, SSLSession sslSession) {
                // 验证请求的主机名称，这里假设只能请求服务端配置的主机名
                // if (Objects.equals("192.168.2.81", hostName)) {
                //     return true;
                // }
                // System.out.println("主机名称校验失败");
                return true;
            }
        };
        // 设置连接的主机名称校验
        HttpsURLConnection.setDefaultHostnameVerifier(hostnameVerifier);
        // 设置连接的安全套接字工厂
        HttpsURLConnection.setDefaultSSLSocketFactory(socketFactory);
        URL url = new URL(path);
        URLConnection conn = url.openConnection();
        String content = ((String) conn.getContent());
        System.out.println("收到消息：" + content);
    }
}
